package com.coder520.foregroundservicetest;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import static android.app.PendingIntent.FLAG_NO_CREATE;

/**
 * Created by huang on 2017/7/11.
 */

public class BackgroundService extends Service {
    public static final String ACTION_SWITCH_TO_FOREGROUND =
            "com.coder520.foregroundservicetest.SWITCH_TO_FOREGROUND";
    public static final String ACTION_STOP_SERVICE =
            "com.coder520.foregroundservicetest.STOP_SERVICE";
    private static final String TAG = BackgroundService.class.getSimpleName();
    private int mId = 0;
    private volatile boolean mStop = false;
    private Object mLock = new Object();

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null && ACTION_SWITCH_TO_FOREGROUND.equals(intent.getAction())) {
            Intent serviceIntent = new Intent(this, BackgroundService.class);
            serviceIntent.setAction(ACTION_STOP_SERVICE);
            PendingIntent pendingIntent = PendingIntent.getService(this, 1, serviceIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            Notification notification = new Notification.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("我是一个前台service")
                    .setContentText("我的一个前台service, 我的优先级很高")
                    .setContentIntent(pendingIntent)
                    .build();
            startForeground(2 , notification);
            return super.onStartCommand(intent, flags, startId);
        }
        if (intent != null && ACTION_STOP_SERVICE.equals(intent.getAction())) {
            stopSelf();
            return super.onStartCommand(intent, flags, startId);
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (mLock) {
                    while (!mStop) {
                        Log.d(TAG, "coder520 current int is :" + mId++);
                        try {
                            mLock.wait(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "coder520 onDestroy called");
        stopForeground(true);
        synchronized (mLock) {
            mStop = true;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
